package org.jeecg.modules.door.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartment;
import org.jeecg.modules.basic.demo.apartment.service.ILwgyBaseApartmentService;
import org.jeecg.modules.door.abutment;
import org.jeecg.modules.door.entity.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.door.vo.LwgyJointDoorPage;
import org.jeecg.modules.door.service.ILwgyJointDoorService;
import org.jeecg.modules.door.service.ILwgyDoorPasswordService;
import org.jeecg.modules.door.service.ILwgyDoorCardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
/*import com.alibaba.fastjson.JSON;*/
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


 /**
 * @Description: 门锁管理
 * @Author: jeecg-boot
 * @Date:   2023-08-08
 * @Version: V1.0
 */
@Api(tags="门锁管理")
@RestController
@RequestMapping("/door/lwgyJointDoor")
@Slf4j
public class LwgyJointDoorController {
	@Autowired
	private ILwgyJointDoorService lwgyJointDoorService;
	@Autowired
	private ILwgyDoorPasswordService lwgyDoorPasswordService;
	@Autowired
	private ILwgyDoorCardService lwgyDoorCardService;
	 @Autowired
	 private ILwgyBaseApartmentService lwgyBaseApartmentService;

	/* @Autowired
	 private RedisTemplate<String, Object> redisTemplate;*/
	@Autowired
	private RedisUtil redisUtil;


	 /**
	  * 自定义分页列表查询
	  *
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "门锁管理-分页列表查询")
	 @ApiOperation(value = "门锁管理-分页列表查询", notes = "门锁管理-分页列表查询")
	 @GetMapping(value = "listDoor")
	 public Result<?> queryPageListDoor(
			 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			 @RequestParam(name = "id",required = false) String id,
			 HttpServletRequest req) {
		 LwgyBaseApartment lwgyBaseApartment = lwgyBaseApartmentService.getById(id);
		 String type = lwgyBaseApartment.getType();
		 LwgyJointDoor lwgyJointDoor = new LwgyJointDoor();
		 QueryWrapper<LwgyJointDoor> queryWrapper = QueryGenerator.initQueryWrapper(lwgyJointDoor, req.getParameterMap());
		 Page<LwgyJointDoor> page = new Page<>(pageNo, pageSize);

		 if (type != null) {
			 if ("school".equals(type)) {
				 queryWrapper.eq("apartment4.id",id);
			 } else if ("campus".equals(type)) {
				 queryWrapper.eq("apartment4.id",id);
			 } else if ("building".equals(type)) {
				 queryWrapper.eq("apartment3.id",id);
			 } else if ("unit".equals(type)) {
				 queryWrapper.eq("apartment2.id",id);
			 } else if ("layer".equals(type)) {
				 queryWrapper.eq("apartment1.id",id);
			 } else if ("room".equals(type)) {
				 queryWrapper.eq("apartment.id",id);
			 }
		 }

		 queryWrapper.eq("apartment.type","room");

		 IPage<LwgyJointDoor> pageList2 = lwgyJointDoorService.queryPageListCustom(page, queryWrapper);
		 return Result.OK(pageList2);
	 }

	/**
	 * 分页列表查询
	 *
	 * @param lwgyJointDoor
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "门锁管理-分页列表查询")
	@ApiOperation(value="门锁管理-分页列表查询", notes="门锁管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(LwgyJointDoor lwgyJointDoor,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<LwgyJointDoor> queryWrapper = QueryGenerator.initQueryWrapper(lwgyJointDoor, req.getParameterMap());
		Page<LwgyJointDoor> page = new Page<LwgyJointDoor>(pageNo, pageSize);
		IPage<LwgyJointDoor> pageList = lwgyJointDoorService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param lwgyJointDoorPage
	 * @return
	 */
	@AutoLog(value = "门锁管理-添加")
	@ApiOperation(value="门锁管理-添加", notes="门锁管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody LwgyJointDoorPage lwgyJointDoorPage) {
		LwgyJointDoor lwgyJointDoor = new LwgyJointDoor();
		BeanUtils.copyProperties(lwgyJointDoorPage, lwgyJointDoor);
		lwgyJointDoorService.saveMain(lwgyJointDoor, lwgyJointDoorPage.getLwgyDoorPasswordList(),lwgyJointDoorPage.getLwgyDoorCardList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param lwgyJointDoorPage
	 * @return
	 */
	@AutoLog(value = "门锁管理-编辑")
	@ApiOperation(value="门锁管理-编辑", notes="门锁管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody LwgyJointDoorPage lwgyJointDoorPage) {
		LwgyJointDoor lwgyJointDoor = new LwgyJointDoor();
		BeanUtils.copyProperties(lwgyJointDoorPage, lwgyJointDoor);
		LwgyJointDoor lwgyJointDoorEntity = lwgyJointDoorService.getById(lwgyJointDoor.getId());
		if(lwgyJointDoorEntity==null) {
			return Result.error("未找到对应数据");
		}
		lwgyJointDoorService.updateMain(lwgyJointDoor, lwgyJointDoorPage.getLwgyDoorPasswordList(),lwgyJointDoorPage.getLwgyDoorCardList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "门锁管理-通过id删除")
	@ApiOperation(value="门锁管理-通过id删除", notes="门锁管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		lwgyJointDoorService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "门锁管理-批量删除")
	@ApiOperation(value="门锁管理-批量删除", notes="门锁管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.lwgyJointDoorService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "门锁管理-通过id查询")
	@ApiOperation(value="门锁管理-通过id查询", notes="门锁管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		LwgyJointDoor lwgyJointDoor = lwgyJointDoorService.getById(id);
		if(lwgyJointDoor==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(lwgyJointDoor);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "密码管理通过主表ID查询")
	@ApiOperation(value="密码管理主表ID查询", notes="密码管理-通主表ID查询")
	@GetMapping(value = "/queryLwgyDoorPasswordByMainId")
	public Result<?> queryLwgyDoorPasswordListByMainId(@RequestParam(name="id",required=true) String id) {
		List<LwgyDoorPassword> lwgyDoorPasswordList = lwgyDoorPasswordService.selectByMainId(id);
		return Result.OK(lwgyDoorPasswordList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ic卡设置通过主表ID查询")
	@ApiOperation(value="ic卡设置主表ID查询", notes="ic卡设置-通主表ID查询")
	@GetMapping(value = "/queryLwgyDoorCardByMainId")
	public Result<?> queryLwgyDoorCardListByMainId(@RequestParam(name="id",required=true) String id) {
		List<LwgyDoorCard> lwgyDoorCardList = lwgyDoorCardService.selectByMainId(id);
		return Result.OK(lwgyDoorCardList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param lwgyJointDoor
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyJointDoor lwgyJointDoor,
								  @RequestParam(name = "id",required = false) String id) {
      // Step.1 组装查询条件查询数据
     // QueryWrapper<LwgyJointDoor> queryWrapper = QueryGenerator.initQueryWrapper(lwgyJointDoor, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
		if(oConvertUtils.isEmpty(id)){
			id="1";
		}
		LwgyBaseApartment lwgyBaseApartment = lwgyBaseApartmentService.getById(id);
		String type = lwgyBaseApartment.getType();

		QueryWrapper<LwgyJointDoor> queryWrapper = new QueryWrapper<LwgyJointDoor>();

		if (type != null) {
			if ("school".equals(type)) {
				queryWrapper.eq("apartment4.id",id);
			} else if ("campus".equals(type)) {
				queryWrapper.eq("apartment4.id",id);
			} else if ("building".equals(type)) {
				queryWrapper.eq("apartment3.id",id);
			} else if ("unit".equals(type)) {
				queryWrapper.eq("apartment2.id",id);
			} else if ("layer".equals(type)) {
				queryWrapper.eq("apartment1.id",id);
			} else if ("room".equals(type)) {
				queryWrapper.eq("apartment.id",id);
			}
		}

		queryWrapper.eq("apartment.type","room");


      List<LwgyJointDoor> queryList = lwgyJointDoorService.queryCustom(queryWrapper);
      System.out.println("-------------------------:"+queryList);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<LwgyJointDoor> lwgyJointDoorList = new ArrayList<LwgyJointDoor>();
      if(oConvertUtils.isEmpty(selections)) {
          lwgyJointDoorList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          lwgyJointDoorList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<LwgyJointDoorPage> pageList = new ArrayList<LwgyJointDoorPage>();
      for (LwgyJointDoor main : lwgyJointDoorList) {
          LwgyJointDoorPage vo = new LwgyJointDoorPage();
          BeanUtils.copyProperties(main, vo);
          List<LwgyDoorPassword> lwgyDoorPasswordList = lwgyDoorPasswordService.selectByMainId(main.getId());
          vo.setLwgyDoorPasswordList(lwgyDoorPasswordList);
          List<LwgyDoorCard> lwgyDoorCardList = lwgyDoorCardService.selectByMainId(main.getId());
          vo.setLwgyDoorCardList(lwgyDoorCardList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "门锁管理列表");
      mv.addObject(NormalExcelConstants.CLASS, LwgyJointDoorPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("门锁管理数据", "导出人:"+sysUser.getRealname(), "门锁管理"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<LwgyJointDoorPage> list = ExcelImportUtil.importExcel(file.getInputStream(), LwgyJointDoorPage.class, params);


              for (LwgyJointDoorPage page : list) {
                  LwgyJointDoor po = new LwgyJointDoor();
                  //doorNo为空，id不空，说明原来有绑定门锁，现在没有，走删除
				  if(oConvertUtils.isEmpty(page.getDoorNo()) && oConvertUtils.isNotEmpty(page.getId())){

					  lwgyJointDoorService.delMain(page.getId());
				  }
				  else if(oConvertUtils.isNotEmpty(page.getDoorNo()) && oConvertUtils.isEmpty(page.getId())){
					  //doorNo不空，id空，说明新加上的门锁关联，原来没有，新增
                  	//给id 赋默认值
					  String targetId = UUIDGenerator.generate();
					  page.setId(targetId);
					  BeanUtils.copyProperties(page, po);
					  lwgyJointDoorService.saveMain(po, page.getLwgyDoorPasswordList(),page.getLwgyDoorCardList());
				  }else{
				  	//其余，修改
					  BeanUtils.copyProperties(page, po);
					  lwgyJointDoorService.updateMain(po, page.getLwgyDoorPasswordList(),page.getLwgyDoorCardList());
				  }

              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }


	@AutoLog(value = "从第三方获取门锁信息-鑫家智能")
	@ApiOperation(value="从第三方获取门锁信息-鑫家智能", notes="从第三方获取门锁信息-鑫家智能")
	@GetMapping(value = "/getOtherApartment")
	public Result<?> getOtherApartment() {
		try {
			abutment a = new abutment();
			String token = a.Authentication();
			System.out.println("token:" + token);
			if (StringUtils.isEmpty(token)) {
				return Result.error("没有获取到token");
			}

			String roomList = a.openSmartRoomList("openSmartRoomList", token, "0", "50");

			//{"resultCode":400,"msgId":1575953421,"reason":"服务能力openSmartRoomList找不到"}
			JSONObject json = JSONObject.fromObject(roomList);
			JSONObject data = json.getJSONObject("data");
			int listSum = data.getInt("listSum");//总记录数
			int totalPages = data.getInt("totalPages");//总页数

			for (int page = 1; page <= totalPages; page++) {
				int count = page * 50;
				roomList = a.openSmartRoomList("openSmartRoomList", token, page + "", count + "");


				json = JSONObject.fromObject(roomList);
				data = json.getJSONObject("data");
				JSONArray fjList = json.getJSONArray("list");
				List<LwgyJointDoor> list = new ArrayList<>();
				for (int i = 0; i < fjList.size(); i++) {
					JSONObject jsonObject1 = fjList.getJSONObject(i);
					String buildingId = jsonObject1.getString("buildingId");
					String buildingName = jsonObject1.getString("buildingName");
					String floorId = jsonObject1.getString("floorId");
					String floorName = jsonObject1.getString("floorName");
					String roomId = jsonObject1.getString("roomId");
					String roomName = jsonObject1.getString("roomName");
					String lockCode = jsonObject1.getString("lockCode");

					LwgyJointDoor lwgyJointDoor = new LwgyJointDoor();
					lwgyJointDoor.setId(roomId);
					lwgyJointDoor.setThirdBuildingId(buildingId);
					lwgyJointDoor.setThirdBuildingName(buildingName);
					lwgyJointDoor.setThirdFloorId(floorId);
					lwgyJointDoor.setThirdFloorName(floorName);
					lwgyJointDoor.setThirdRoomId(roomId);
					lwgyJointDoor.setThirdRoomName(roomName);
					lwgyJointDoor.setDoorNo(lockCode);
					list.add(lwgyJointDoor);
				}
				lwgyJointDoorService.saveOrUpdateBatch(list);
			}

			return Result.OK();

			}catch(Exception e){
					return Result.error("同步出错，请联系管理员");
		}
	}


	 /**
	  *   读取鲁维门锁信息
	  *
	  * @param lwgyJointDoor
	  * @return
	  */
	 @AutoLog(value = "门锁管理-读取鲁维门锁信息")
	 @ApiOperation(value="门锁管理-读取鲁维门锁信息", notes="门锁管理-读取鲁维门锁信息")
	 @PutMapping(value = "/doorInfo")
	 public Result<?> doorInfo(@RequestBody LwgyJointDoor lwgyJointDoor) {
		 try{

			 lwgyJointDoorService.doorInfo(lwgyJointDoor.getDoorNo());
			 return Result.OK("指令下发成功，请刷新查看！");
		 }catch (Exception e){
			 return Result.OK("读取失败！");
		 }

	 }

 }
